<template>
  <div class="check-statistics-container">
    <h2>盘点统计分析</h2>
    
    <el-card class="filter-card">
      <div class="filter-controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="loadStatistics"
        ></el-date-picker>
        <el-select v-model="planType" size="small" @change="loadStatistics">
          <el-option label="全部类型" value="all"></el-option>
          <el-option label="月度盘点" value="monthly"></el-option>
          <el-option label="季度盘点" value="quarterly"></el-option>
          <el-option label="年度盘点" value="yearly"></el-option>
          <el-option label="部门盘点" value="dept"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="exportStatistics">导出统计</el-button>
      </div>
    </el-card>
    
    <el-row :gutter="20">
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ totalPlans }}</div>
            <div class="stat-label">盘点计划总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ completedPlans }}</div>
            <div class="stat-label">已完成计划数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ overallCompletionRate }}</div>
            <div class="stat-label">整体完成率</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ totalAssets }}</div>
            <div class="stat-label">参与盘点资产总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ checkedAssets }}</div>
            <div class="stat-label">已盘点资产数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="8">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ diffAssets }}</div>
            <div class="stat-label">差异资产数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>盘点计划完成情况</span>
            </div>
          </template>
          <div ref="planStatusChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>盘点差异类型分布</span>
            </div>
          </template>
          <div ref="diffTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>盘点效率分析</span>
            </div>
          </template>
          <div ref="efficiencyChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-card class="table-card">
      <div class="table-header">
        <span>盘点计划详细统计</span>
      </div>
      <el-table :data="planStatistics" style="width: 100%" border>
        <el-table-column prop="planNo" label="计划编号" width="150"></el-table-column>
        <el-table-column prop="planName" label="计划名称"></el-table-column>
        <el-table-column prop="planType" label="计划类型" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" :type="getPlanTypeTagType(scope.row.planType)">{{ scope.row.planType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAssets" label="资产总数" width="100" align="center"></el-table-column>
        <el-table-column prop="checkedAssets" label="已盘资产" width="100" align="center"></el-table-column>
        <el-table-column prop="diffAssets" label="差异资产" width="100" align="center"></el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="100" align="center">
          <template #default="scope">
            <el-progress :percentage="parseInt(scope.row.completionRate)" :show-text="false" size="small"></el-progress>
            <span>{{ scope.row.completionRate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'CheckStatistics',
  setup() {
    const dateRange = ref([])
    const planType = ref('all')
    
    // 图表容器引用
    const planStatusChart = ref(null)
    const diffTypeChart = ref(null)
    const efficiencyChart = ref(null)
    
    // 图表实例
    const chartInstances = ref({
      planStatus: null,
      diffType: null,
      efficiency: null
    })
    
    // 统计数据
    const planStatistics = ref([])
    const totalPlans = ref(0)
    const completedPlans = ref(0)
    const overallCompletionRate = ref('0%')
    const totalAssets = ref(0)
    const checkedAssets = ref(0)
    const diffAssets = ref(0)
    
    // 加载统计数据
    const loadStatistics = async () => {
      try {
        const params = {
          startDate: dateRange.value[0] ? dateRange.value[0].toISOString().split('T')[0] : '',
          endDate: dateRange.value[1] ? dateRange.value[1].toISOString().split('T')[0] : '',
          planType: planType.value
        }
        
        const response = await axios.get('/api/check/statistics', {
          params
        })
        
        if (response.code === 200 && response.data) {
          updateStatisticsData(response.data)
          initCharts()
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取盘点统计数据失败:', error)
        setMockData()
      }
    }
    
    // 更新统计数据
    const updateStatisticsData = (data) => {
      planStatistics.value = data.planStatistics || []
      totalPlans.value = data.totalPlans || 0
      completedPlans.value = data.completedPlans || 0
      overallCompletionRate.value = data.overallCompletionRate || '0%'
      totalAssets.value = data.totalAssets || 0
      checkedAssets.value = data.checkedAssets || 0
      diffAssets.value = data.diffAssets || 0
    }
    
    // 设置模拟数据
    const setMockData = () => {
      planStatistics.value = [
        {
          planNo: 'CP20241101001',
          planName: '2024年11月月度盘点',
          planType: '月度盘点',
          totalAssets: 500,
          checkedAssets: 485,
          diffAssets: 15,
          completionRate: '97%',
          startDate: '2024-11-01',
          endDate: '2024-11-05',
          status: '已完成'
        },
        {
          planNo: 'CP20241001001',
          planName: '2024年10月月度盘点',
          planType: '月度盘点',
          totalAssets: 480,
          checkedAssets: 480,
          diffAssets: 0,
          completionRate: '100%',
          startDate: '2024-10-01',
          endDate: '2024-10-05',
          status: '已完成'
        },
        {
          planNo: 'CP2024Q4001',
          planName: '2024年第四季度盘点',
          planType: '季度盘点',
          totalAssets: 1200,
          checkedAssets: 800,
          diffAssets: 25,
          completionRate: '66.67%',
          startDate: '2024-10-15',
          endDate: '2024-12-31',
          status: '进行中'
        },
        {
          planNo: 'CP2024IT001',
          planName: 'IT部门专项盘点',
          planType: '部门盘点',
          totalAssets: 300,
          checkedAssets: 300,
          diffAssets: 8,
          completionRate: '100%',
          startDate: '2024-09-10',
          endDate: '2024-09-15',
          status: '已完成'
        },
        {
          planNo: 'CP20240801001',
          planName: '2024年8月月度盘点',
          planType: '月度盘点',
          totalAssets: 450,
          checkedAssets: 450,
          diffAssets: 12,
          completionRate: '100%',
          startDate: '2024-08-01',
          endDate: '2024-08-05',
          status: '已完成'
        }
      ]
      
      // 计算汇总数据
      totalPlans.value = planStatistics.value.length
      completedPlans.value = planStatistics.value.filter(p => p.status === '已完成').length
      totalAssets.value = planStatistics.value.reduce((sum, p) => sum + p.totalAssets, 0)
      checkedAssets.value = planStatistics.value.reduce((sum, p) => sum + p.checkedAssets, 0)
      diffAssets.value = planStatistics.value.reduce((sum, p) => sum + p.diffAssets, 0)
      overallCompletionRate.value = totalAssets.value > 0 ? 
        Math.round((checkedAssets.value / totalAssets.value) * 100) + '%' : '0%'
      
      initCharts()
    }
    
    // 初始化图表
    const initCharts = () => {
      nextTick(() => {
        initPlanStatusChart()
        initDiffTypeChart()
        initEfficiencyChart()
      })
    }
    
    // 初始化计划状态图表
    const initPlanStatusChart = () => {
      if (!planStatusChart.value) return
      
      if (chartInstances.value.planStatus) {
        chartInstances.value.planStatus.dispose()
      }
      
      chartInstances.value.planStatus = echarts.init(planStatusChart.value)
      
      // 统计计划状态
      const statusCount = {
        '已完成': 0,
        '进行中': 0,
        '未开始': 0,
        '已取消': 0
      }
      
      planStatistics.value.forEach(plan => {
        statusCount[plan.status] = (statusCount[plan.status] || 0) + 1
      })
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '计划状态',
          type: 'pie',
          radius: '60%',
          center: ['60%', '50%'],
          data: Object.keys(statusCount).map(key => ({
            name: key,
            value: statusCount[key]
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      chartInstances.value.planStatus.setOption(option)
    }
    
    // 初始化差异类型图表
    const initDiffTypeChart = () => {
      if (!diffTypeChart.value) return
      
      if (chartInstances.value.diffType) {
        chartInstances.value.diffType.dispose()
      }
      
      chartInstances.value.diffType = echarts.init(diffTypeChart.value)
      
      // 模拟差异类型数据
      const diffTypeData = [
        { name: '盘亏', value: 20 },
        { name: '盘盈', value: 15 },
        { name: '状态不符', value: 10 },
        { name: '位置不符', value: 5 },
        { name: '其他', value: 3 }
      ]
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: diffTypeData.map(item => item.name)
        },
        series: [{
          name: '差异数量',
          type: 'bar',
          data: diffTypeData.map(item => item.value),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          label: {
            show: true,
            position: 'right'
          }
        }]
      }
      
      chartInstances.value.diffType.setOption(option)
    }
    
    // 初始化效率分析图表
    const initEfficiencyChart = () => {
      if (!efficiencyChart.value) return
      
      if (chartInstances.value.efficiency) {
        chartInstances.value.efficiency.dispose()
      }
      
      chartInstances.value.efficiency = echarts.init(efficiencyChart.value)
      
      // 模拟效率数据
      const efficiencyData = planStatistics.value.map(plan => ({
        name: plan.planName.length > 10 ? plan.planName.substring(0, 10) + '...' : plan.planName,
        计划总数: plan.totalAssets,
        已盘数量: plan.checkedAssets,
        差异数量: plan.diffAssets
      }))
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['计划总数', '已盘数量', '差异数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: efficiencyData.map(item => item.name),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '计划总数',
            type: 'bar',
            stack: '总量',
            emphasis: {
              focus: 'series'
            },
            data: efficiencyData.map(item => item.计划总数)
          },
          {
            name: '已盘数量',
            type: 'bar',
            stack: '已盘',
            emphasis: {
              focus: 'series'
            },
            data: efficiencyData.map(item => item.已盘数量)
          },
          {
            name: '差异数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: efficiencyData.map(item => item.差异数量)
          }
        ]
      }
      
      chartInstances.value.efficiency.setOption(option)
    }
    
    // 获取计划类型标签类型
    const getPlanTypeTagType = (type) => {
      const typeMap = {
        '月度盘点': 'primary',
        '季度盘点': 'success',
        '年度盘点': 'warning',
        '部门盘点': 'info'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        '已完成': 'success',
        '进行中': 'primary',
        '未开始': 'info',
        '已取消': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 导出统计
    const exportStatistics = () => {
      console.log('导出盘点统计数据')
      alert('盘点统计数据导出成功')
    }
    
    onMounted(() => {
      // 设置默认日期范围为最近3个月
      const endDate = new Date()
      const startDate = new Date()
      startDate.setMonth(startDate.getMonth() - 3)
      dateRange.value = [startDate, endDate]
      
      loadStatistics()
      
      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        Object.values(chartInstances.value).forEach(instance => {
          if (instance) {
            instance.resize()
          }
        })
      })
    })
    
    return {
      dateRange,
      planType,
      planStatusChart,
      diffTypeChart,
      efficiencyChart,
      planStatistics,
      totalPlans,
      completedPlans,
      overallCompletionRate,
      totalAssets,
      checkedAssets,
      diffAssets,
      getPlanTypeTagType,
      getStatusTagType,
      loadStatistics,
      exportStatistics
    }
  }
}
</script>

<style scoped>
.check-statistics-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

.filter-controls .el-date-picker {
  width: 300px;
}

.filter-controls .el-select {
  width: 150px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  margin-bottom: 20px;
  font-weight: bold;
}

.table-header span {
  font-size: 16px;
  color: #303133;
}
</style>